package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.adapter.DubVideoRecordingAdapter;
import com.ciwong.epaper.modules.epaper.bean.CorrectLinesRelut;
import com.ciwong.epaper.modules.epaper.bean.CorrectLinesWordsRelut;
import com.ciwong.epaper.modules.epaper.bean.CorrectRelut;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.RecordSubmitAsyncPart;
import com.ciwong.epaper.modules.epaper.bean.SentenceAnswer;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.LswRequest;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.SentenceAnswerBean;
import com.ciwong.epaper.modules.evaluate.bean.SentencesDetail;
import com.ciwong.epaper.modules.evaluate.bean.SubmitResult;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.i.OnLoadMoreListener;
import com.ciwong.epaper.modules.me.i.RecordInterFace;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.msg.bean.WorkContent;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.Base64Utils;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DateUtils;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IVUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.KHBVideo.KHBUtils;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayer;
import com.ciwong.epaper.util.KHBVideo.KHBVideoPlayerStandard;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.ScoreUtils;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.widget.PlayStateDubView;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.toast.ZToast;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.audio.recorder.OnRecorderListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.BaseQuickOnItemClickListener;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.frank.ffmpeg.handler.FFmpegHandler;
import com.frank.ffmpeg.util.FFmpegUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_BEGIN;
import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_ERROR;
import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_FINISH;
import static com.frank.ffmpeg.handler.FFmpegHandler.MSG_PROGRESS;

/**
 * 配音录制页面
 */
public class DubVideoRecordingActivity extends BaseActivity
        implements View.OnClickListener, RecordInterFace {
    private final String TAG = "DubVideoRecordingActivity";

    private RecyclerView mRvBookDesk;

    private DubVideoRecordingAdapter mDubVideoRecordingAdapter;

    private LinearLayout llDubingDoing;

    private VideoView mVideoView;

    private MediaPlayer mMediaPlayer;

    private SeekBar mSeekBar;

    private TextView tvCurrent, tvTotal;

    private LinearLayout llDubingResult;

    private KHBVideoPlayerStandard mKHBVideoPlayerStandard;

    private ImageView ivDubResultFinishTag;

    private ImageView ivDubResultScoreTag;

    private RelativeLayout rlDubResultScore;

    private TextView txDubResultScore;

    private TextView txDubResultScoreTag;

    private TextView txDubResultTip;

    private TextView txDubResultSentencesNum;

    private TextView txDubResultTag;

    private LinearLayout rlDubResultSubmit;

    private TextView txDubResultSubmit;

    private ImageView txDubResultWXImg;

    private RelativeLayout txDubResultRelatWX;

    private SubmitResult submitResult;

    private Context mContext;

    private String doWorkId;

    public static int readCount = 0;

    private boolean isSoundToLow = true;
    /**
     * 是否已评分
     */
    private boolean oldHasGrade;

    /**
     * 年级id
     */
    private int mGradeId;

    /**
     * 完成录音
     */
    private LinearLayout rlDubVideoConcat;

    /**
     * 视频资源
     */
    private WorkContent mWorkContent;

    /**
     * 作业id（练习模式为“”）
     */
    private String workId = "";

    /**
     * 作业的班级id
     */
    private String classId = "0";

    /**
     * 作业内容id
     */
    private int contentId = 0;

    /**
     * 句子资源
     */
    public ArrayList<Sentence> sentences = new ArrayList<Sentence>();

    /**
     * 视频原始地址
     */
    private String localVideoPath;

    /**
     * 视频处理消人声地址(用于获取背景音)
     */
    private String localMuxVideoPath;

    /**
     * 视频处理纯视频地址（用于合成完整视频）
     */
    private String localOnlyVideoPath;

    /**
     * 视频处理纯声音背景地址（用于合成带配音的的视频音轨）
     */
    private String localMuxAudioPath;

    /**
     * 音频合成带背景音配音地址
     */
    private String localDubAudioPath;

    /**
     * 视频合成带背景音地址
     */
    private String localMixDubVideoPath;

    private String title;

    /**
     * 加载状态
     */
    private int preparStatus = VIDEO_UNPREPARED;

    private final static int VIDEO_UNPREPARED = 0;

    private final static int VIDEO_PREPARED = 1;

    /**
     * 播放状态
     */
    private int playStatus = PLAY_UNPLAY;

    private final static int PLAY_UNPLAY = 0;

    private final static int PLAY_PLAYING = 1;

    private final static int PLAY_PAUSE = 2;

    private final static int PLAY_STOP = 3;

    private DubVideoRecordingAdapter.BookDeskViewHolder currViewHolde;

    private int currPosition = -1;

    private boolean isPlayVideo = false;

    private boolean isVolumeVideo = false;

    private boolean isRecord = false;

    private boolean isPlayDubVideo = false;

    private int currEndTime = 0;

    private CWDialog mDialog;

    private int videoDuration = 1000;

    private int int_ffmpeg = 0;

    private String downloadMsg = "视频处理中...";

    private FFmpegHandler ffmpegHandler;

    /**
     * 配音转态，0为完成，1已完成，
     */
    private int dub_status = 0;

    /**
     * 是否有背景音
     */
    private boolean haveBgAudio = false;

    private ArrayList<SentenceAnswerBean> sentenceAnswers = new ArrayList<>();

    // 要提交的数据
    private SentenceAnswer sentenceAnswerModle;

    private boolean isCheckSubmit = false;

    /**
     * 1：配音中、2：完成合成、3：完成上传
     */
    private int dubViewStatus = 1;

    /**
     * 做作业耗时
     */
    private int totalTime = 0;

    /**
     * 作业总得分
     */
    private float sumScore;

    /**
     * 作业开始时间
     */
    private long startDate = System.currentTimeMillis();

    private long workStartTime;

    /**
     * 新需求全部走api 评测，所以要另外录音文件
     */
    protected Mp3Recorder mp3Recorder;

    /**
     * 录音分贝
     */
    private int mRecordSoundDb;

    protected boolean isRecordFail = false;
    /**
     * 合成次数
     */
    private int mixVideotime = 0;

    private EApplication application;

    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_BEGIN:
                    showDownloadProgress(downloadMsg);
                    break;
                case MSG_FINISH:
                    hideDownloadProgress();
                    if (int_ffmpeg == 1) {
                        CWSys.setSharedBoolean(
                                "isSucces" + mWorkContent.getVersionId(), true);
                        // 处理静音
                        initVideo();
                    } else if (int_ffmpeg == 2) {
                        // 合成配音成功
                        dub_status = 1;
                        showDubingFinishView();
                    }
                    int_ffmpeg = 0;
                    break;
                case MSG_PROGRESS:
                    int progress = msg.arg1;
                    int duration = msg.arg2;
                    if (progress > 0) {
                        updateDownloadProgress(progress);
                    }
                    break;
                case MSG_ERROR:
                    mixVideotime++;
                    if (int_ffmpeg == 2 && mixVideotime < 10) {
                        //合成配音
                        if (getUnRecordPostion() == -1) {
                            composeAllAudio();
                        }
                    } else {
                        hideDownloadProgress();
                        // 发生错误重新录音
                        ZToast.makeText(DubVideoRecordingActivity.this, "合成出了一点问题...",
                                ZToast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private Handler handler = new Handler(Looper.getMainLooper());

    private Runnable startRunnable = new Runnable() {
        public void run() {
            if (mVideoView.isPlaying()) {
                int current = mVideoView.getCurrentPosition();
                mSeekBar.setProgress(current);
                tvCurrent.setText(KHBUtils
                        .stringForTime(mVideoView.getCurrentPosition()));
            }
            handler.postDelayed(startRunnable, 500);
        }
    };
    /**
     * 停止播放视频
     */
    private Runnable stopRunnable = new Runnable() {
        public void run() {
            if (mVideoView.isPlaying()) {
                int current = mVideoView.getCurrentPosition();
                mSeekBar.setProgress(current);
                tvCurrent.setText(KHBUtils
                        .stringForTime(mVideoView.getCurrentPosition()));
                mVideoView.pause();
                handler.removeCallbacks(startRunnable);
                stopPlayAnimation();
                isPlayVideo = false;
            }
        }
    };
    /**
     * 停止录音
     */
    private Runnable stopRecordRunnable = new Runnable() {
        public void run() {
            stopRecord();
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_dub_video_recording;
    }

    @Override
    protected void findViews() {
        llDubingDoing = findViewById(R.id.ll_dubing_doing);
        llDubingResult = findViewById(R.id.ll_dubing_result);
        mRvBookDesk = findViewById(R.id.swipe_target);
        mVideoView = findViewById(R.id.vv_dub_content);
        mSeekBar = findViewById(R.id.sb_video);
        tvCurrent = findViewById(R.id.tv_current);
        tvTotal = findViewById(R.id.tv_total);
        mKHBVideoPlayerStandard = findViewById(R.id.vv_dub_result);
        ivDubResultFinishTag = findViewById(R.id.iv_dub_result_finish_tag);
        ivDubResultScoreTag = findViewById(R.id.iv_dub_result_score_tag);
        rlDubResultScore = findViewById(R.id.rl_dub_result_score);
        txDubResultScore = findViewById(R.id.tx_dub_result_score);
        txDubResultScoreTag = findViewById(R.id.tx_dub_result_score_tag);
        txDubResultTip = findViewById(R.id.tx_dub_result_tip);
        txDubResultSentencesNum = findViewById(
                R.id.tx_dub_result_sentences_num);
        txDubResultTag = findViewById(R.id.tx_dub_result_tag);
        rlDubResultSubmit = findViewById(R.id.rl_dub_result_submit);
        txDubResultSubmit = findViewById(R.id.tx_dub_result_submit);
        txDubResultWXImg = findViewById(R.id.tx_dub_result_wx_img);
        txDubResultRelatWX = findViewById(R.id.tx_dub_result_relat_wx);
    }

    @Override
    protected void initEvent() {
        rlDubResultSubmit.setOnClickListener(this);
        txDubResultWXImg.setOnClickListener(new ViewOnClickListener() {//微信分享
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(1);//微信朋友分享
            }
        });
    }

    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        WxShareHelper.getInstance().initWxShare(DubVideoRecordingActivity.this, new WxShareListener() {
            @Override
            public void onWxShareing(String str) {
                ToastUtil.INSTANCE.toastInCenter(mContext, "分享中...");
            }

            @Override
            public void onWxShareSucc(String var) {
                ToastUtil.INSTANCE.toastCenterSuccess("分享成功");
                shareAddPointType(submitResult.getDoWorkId(), AddPointTypes.SHERE_SCORE);
            }

            @Override
            public void onWxShareFailure(int var, String var1) {
                ToastUtil.INSTANCE.toastCenterError("分享失败");

            }

            @Override
            public boolean onWxShareCancel() {
                ToastUtil.INSTANCE.toastCenter(mContext, "取消分享", R.mipmap.ic_cancel);

                return false;
            }
        });
        ShareMsgObj shareMsgObj = new ShareMsgObj();
        shareMsgObj.setWxType(wxType);//类型：微信朋友1，微信朋友圈2
        shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
        //        shareMsgObj.setMsgTitle(mTitleText);

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.lsw_wx_share);
        shareMsgObj.setThunbBmp(bmp);
        String sharePara = null;


        if (null != submitResult && mWorkContent != null) {
            shareMsgObj.setUrl(getShareBase64Url());
            String shareContent;
            String score = getUserInfoBase().getRealName();
            shareContent = getString(R.string.str_share_py, score);
            if (wxType == 1) {
                shareMsgObj.setMsgTitle(shareContent);
                /*shareMsgObj.setText("配音内容《" + mWorkContent.getResourceName() + "》");*/
                shareMsgObj.setMsgDesription("配音内容《" + mWorkContent.getResourceName() + "》");
            } else if (wxType == 2) {
                shareMsgObj.setMsgTitle(shareContent);
            }
            WxShareHelper.getInstance().sendReq(shareMsgObj);

        }

    }

    public String getShareBase64Url() {
        String shareUrl;
        StringBuffer sb1 = new StringBuffer(EpaperConstant.URL_H5_DUB_VIDEO_RECORD_DETAIL);
        StringBuffer sb = new StringBuffer();
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long useeId = getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(useeId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&doWorkId=");
        sb.append(doWorkId);
        sb.append("&noAlert=1");
        String param = Base64Utils.getBase64(sb.toString());
        shareUrl = sb1.append(param).toString();
        return shareUrl;
    }

    private void shareAddPointType(String doWorkId, String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, doWorkId + "");
    }

    @Override
    protected void init() {
        setValideSource(false);
        mContext = this;
        Intent intent = getIntent();
        mWorkContent = (WorkContent) intent
                .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        classId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        contentId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CONTENTID, 0);
        try {
            if (classId == null || "0".equals(classId)) {
                EApplication application = (EApplication) getBaseApplication();
                Clazz clazz = application.getClazz();
                if (clazz == null) {
                    classId = "0";
                } else {
                    classId = clazz.getClassId() + "";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        workStartTime = CWSys.getSharedLong(getStartTimeKey(), 0);
        if (workStartTime == 0) {
            workStartTime = mWorkContent.getStartTime();
        }
        final String saveUUid = CWSys.getSharedString(RepeatKeyUtil
                        .getDubbingUuidSaveKey(workId, mWorkContent.getVersionId(),
                                mWorkContent.getPackageId(), mWorkContent.getcId(),
                                mWorkContent.getModuleId(), contentId),
                null);
        long strartTime = startDate;
        try {
            strartTime = CWSys.getSharedLong(
                    RepeatKeyUtil.getDubbingStartDateSaveKey(workId,
                            mWorkContent.getVersionId(),
                            mWorkContent.getPackageId(), mWorkContent.getcId(),
                            mWorkContent.getModuleId(), contentId),
                    startDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != saveUUid && workId.length() > 2) {
            mUuid = saveUUid;
            startDate = strartTime;
            CWLog.e(TAG, "######null != saveUUid######" + saveUUid);
        } else {
            CWSys.setSharedString(RepeatKeyUtil.getDubbingUuidSaveKey(workId,
                    mWorkContent.getVersionId(), mWorkContent.getPackageId(),
                    mWorkContent.getcId(), mWorkContent.getModuleId(),
                    contentId), mUuid);
            CWSys.setSharedLong(RepeatKeyUtil.getDubbingStartDateSaveKey(workId,
                    mWorkContent.getVersionId(), mWorkContent.getPackageId(),
                    mWorkContent.getcId(), mWorkContent.getModuleId(),
                    contentId), startDate);
        }
        totalTime = (int) (System.currentTimeMillis() - startDate) / 1000;
        if (totalTime < 0) {
            totalTime = 0;
        }
        initView();
        initData();
        initVideoData();
        ALiYunManager.getInstance().registerListener(aLiYunListener);
        txDubResultRelatWX.setVisibility(View.INVISIBLE);
    }

    public String getStartTimeKey() {
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        String userId = "";
        if (null != userInfo) {
            userId = userInfo.getUserId() + "";
        }
        String key = workId + mWorkContent.getVersionId() + userId + EApplication.BRAND_ID + SerializableManager.SerializeKey.SHARE_KET_WORK_NOW_DATA;
        return key;
    }

    /**
     * 加载配音句子数据
     */
    protected void initData() {
        application = (EApplication) getApplication();
        if (application != null) {
            //服务是否过期
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContent != null && mWorkContent.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        if (EApplication.getInstance().getClazz() != null) {
            mGradeId = EApplication.getInstance().getClazz().getGradeId();
        }
        dub_status = 0;
        isCheckSubmit = false;
        setParagraphText(mWorkContent.getSentences());
        mRvBookDesk.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        mDubVideoRecordingAdapter = new DubVideoRecordingAdapter(
                DubVideoRecordingActivity.this,
                R.layout.item_view_dub_video_recording, sentences, this, serviceExpired);
        mDubVideoRecordingAdapter.addFooterView(getFooterView());
        mRvBookDesk.setAdapter(mDubVideoRecordingAdapter);
        mDubVideoRecordingAdapter.setOnItemClickListener(
                new BaseQuickOnItemClickListener() {
                    @Override
                    public void avertRepeatOnClick(BaseQuickAdapter adapter, View view, int position) {
                        // 点击开始播放
                        showGetSDcardPermissDialog(position);
                    }
                });
        mRvBookDesk.addOnScrollListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (getUnRecordPostion() == -1) {
                    rlDubVideoConcat.setBackgroundColor(
                            getResources().getColor(R.color.green));
                }
            }

            @Override
            public void onUnLoadMore() {
            }
        });
        // 设置评分系数
        ScoreUtils.setSocreCoefficient();
        ffmpegHandler = new FFmpegHandler(mHandler);
    }

    private View getFooterView() {
        View view = LayoutInflater.from(DubVideoRecordingActivity.this).inflate(
                R.layout.dubing_footview_layout,
                (ViewGroup) mRvBookDesk.getParent(), false);
        rlDubVideoConcat = view.findViewById(R.id.rl_dub_video_concat);
        rlDubVideoConcat.setOnClickListener(this);
        return view;
    }

    /**
     * 查看是否有未完成的配音
     *
     * @return
     */
    private int getUnRecordPostion() {
        int rrsult = -1;
        for (int i = 0; i < sentences.size(); i++) {
            Sentence item = sentences.get(i);
            if (!item.hasGrade()) {
                return i;
            }
        }
        return rrsult;
    }

    private LinkedHashMap<String, Integer> getRecordMap() {
        LinkedHashMap<String, Integer> para = new LinkedHashMap<>();
        for (int i = 0; i < sentences.size(); i++) {
            Sentence item = sentences.get(i);
            if (item.hasGrade()) {
                para.put(item.getSoundUrl() + "cut.aac",
                        item.getStart() + item.getDuration());
            }
        }
        return para;
    }

    @Override
    public void startRecordView() {
        showgetRecordPermissDialog();
    }

    @Override
    public void stopRecordView() {
        currViewHolde.play_record_iocn.stopOnlyRecord();
    }

    private PlayStateDubView mLastPlayIcon;

    @Override
    public void playRecordView() {
        if (isRecord || isPlayDubVideo) {
            return;
        }
        Sentence currSentence = sentences.get(currPosition);
        if (!currSentence.hasGrade()) {
            return;
        }
        if (null != mLastPlayIcon) {
            mLastPlayIcon.stopOnlyPlay();
        }
        String soundUrl = currSentence.getSoundUrl();
        File file = new File(soundUrl);
        if (file == null || !file.exists()) {
            soundUrl = FileUtil.getReNameFilePath(soundUrl);
        }
        mLastPlayIcon = currViewHolde.play_dubing_iocn;
        mLastPlayIcon.startPlay();
        if (isPlayVideo) {
            stopPreviousVideo(true);
            if (mVideoView != null) {
                mVideoView.pause();
                isPlayVideo = false;
            }
            isPlayVideo = false;
        }
        AudioPlayer.getInstance().setOnPlayListener(new OnPlayListener() {
            @Override
            public void onReadPlayer(long l, Object o) {

            }

            @Override
            public void onPlayStart(Object o) {

            }

            @Override
            public void stop(Object o) {
                mLastPlayIcon.stopOnlyPlay();
                isPlayDubVideo = false;
            }

            @Override
            public void onError(int i, Object o) {
                mLastPlayIcon.stopOnlyPlay();
                isPlayDubVideo = false;
            }

            @Override
            public void onBuffer(Object o, long l, long l1) {

            }

            @Override
            public void onPlaying(long l, long l1) {

            }
        }).play(BaseConstants.FILE_PREFIX + soundUrl, null);
        playVolumeVideo(currSentence);
        isPlayDubVideo = true;
    }

    /**
     * 加载视频数据
     */
    protected void initVideoData() {
        localVideoPath = ESystem.getDubingVideoPath() + File.separator
                + StringUtils.md5(mWorkContent.getVideoUrl());
        localMuxVideoPath = ESystem.getDubingVideoPath() + File.separator
                + StringUtils.md5(mWorkContent.getVideoUrl()) + "_mux.mp4";
        localOnlyVideoPath = ESystem.getDubingVideoPath() + File.separator
                + StringUtils.md5(mWorkContent.getVideoUrl()) + "_only.mp4";
        localMuxAudioPath = ESystem.getDubingVideoPath() + File.separator
                + StringUtils.md5(mWorkContent.getVideoUrl()) + "_aac.aac";
        localDubAudioPath = getDubingPath().getAbsolutePath();
        localMixDubVideoPath = getMixDubingPath().getAbsolutePath();
        if ("".equals(mWorkContent.getBgAudioUrl())) {
            mWorkContent.setBgAudioUrl(
                    "https://rimg3.ciwong.net/6v68/tools/audios/bgTemplate.mp3");
        }
        if (mWorkContent.getBgAudioUrl() != null
                && !"".equals(mWorkContent.getBgAudioUrl())) {
            localMuxAudioPath = ESystem.getDubingVideoPath() + File.separator
                    + StringUtils.md5(mWorkContent.getBgAudioUrl()) + ".mp3";
            File targetAudioFile = new File(localMuxAudioPath);
            if (targetAudioFile.exists()) {
                haveBgAudio = true;
            } else {
                finish();
            }
        }
        File localVideoFile = new File(localVideoPath);
        if (!localVideoFile.exists()) {
            finish();
        }
        boolean isNeedFFmpeg = false;
        boolean isSucces = CWSys.getSharedBoolean(
                "isSucces" + mWorkContent.getVersionId(), false);
        List<String[]> commandList = new ArrayList<>();
        if (!haveBgAudio) {
            File localMuxVideoFile = new File(localMuxVideoPath);
            if (!localMuxVideoFile.exists() || !isSucces) {
                String[] extractVideo = FFmpegUtil
                        .clearManVolVideo(localVideoPath, localMuxVideoPath);
                commandList.add(extractVideo);
                isNeedFFmpeg = true;
            }
        }
        File localOnlyVideoFile = new File(localOnlyVideoPath);
        if (!localOnlyVideoFile.exists() || !isSucces) {
            String[] keyintCmd = FFmpegUtil.extractVideo(localVideoPath,
                    localOnlyVideoPath);
            commandList.add(keyintCmd);
            isNeedFFmpeg = true;
        }
        if (!haveBgAudio) {
            File localMuxAudioFile = new File(localMuxAudioPath);
            if (!localMuxAudioFile.exists() || !isSucces) {
                String[] extractAudio = FFmpegUtil
                        .extractAudio(localMuxVideoPath, localMuxAudioPath);
                commandList.add(extractAudio);
                isNeedFFmpeg = true;
            }
        }
        if (isNeedFFmpeg || !isSucces) {
            composeMusicAndAudioAndKeyint(commandList);
        } else {
            initVideo();
        }
        // testFFmpeg();
    }

    /**
     * 测试命令
     */
    private void testFFmpeg() {
        String demo = "ffmpeg,-y,-i,/storage/emulated/0/ciwong/newspaper/dubing/video/4dd4095d919875c2328b26d47126d68b_aac.aac,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/965c96072bcb9c58555dc54d2ecda7fc.mp3,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/98ca57bd4d5e8772e4db366709c7f25f.mp3,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/14153e066ae02e5cf1df29146a01ea33.mp3,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/e690b0ea952b5629db77ed151dcdb243.mp3,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/6e80ad7c96300c5841b14c554f078b4d.mp3,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/dc25cc8ffe1ff6869716c6e71b2d213d.mp3,-i,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/3156bc3f580bdfb6c63a3a16bd06f1d0.mp3,-filter_complex,[1]adelay=1316|2710[1_];  [2]adelay=4793|1997[2_];  [3]adelay=7510|3566[3_];  [4]adelay=14075|3424[4_];  [5]adelay=17789|3979[5_];  [6]adelay=24475|4316[6_];  [7]adelay=29319|851[7_];  [0][1_][2_][3_][4_][5_][6_][7_]amix=8,/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/5746449505090924736_dubing.aac";
        String[] extractAudioAndVideo = FFmpegUtil.mediaMux(
                "/storage/emulated/0/ciwong/newspaper/dubing/video/4dd4095d919875c2328b26d47126d68b_only.mp4",
                "/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/5746449505090924736_dubing.aac",
                "/storage/emulated/0/ciwong/newspaper/dubing/answers/831515/5746449505090924736/1ab6678e-b513-429d-af63-5ac71d9136a6/5746449505090924736_mix_dubing.mp4");
        String[] common = FFmpegUtil.transCmd(demo, ",");
        CWLog.d(TAG, common.toString());
        if (ffmpegHandler != null) {
            int_ffmpeg = 0;
            downloadMsg = "视频预处理中...";
            ffmpegHandler.executeFFmpegCmd(extractAudioAndVideo);
        }
    }

    /**
     * 视频预处理分段播放
     *
     * @param commandList
     */
    private void composeMusicAndAudioAndKeyint(List<String[]> commandList) {
        if (ffmpegHandler != null) {
            int_ffmpeg = 1;
            downloadMsg = "视频预处理中...";
            ffmpegHandler.executeFFmpegCmds(commandList);
        }
    }

    /**
     * 加载视频数据
     */
    protected void initVideo() {
        preparStatus = VIDEO_UNPREPARED;
        playStatus = PLAY_UNPLAY;
        mKHBVideoPlayerStandard.setNormalView(true);
        IVUtils.setImageWidth200(mKHBVideoPlayerStandard.thumbImageView,
                mWorkContent.getCover());
        mVideoView.setVideoPath(localVideoPath);
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mMediaPlayer = mediaPlayer;
                // 视频加载完毕
                mSeekBar.setMax(mVideoView.getDuration());
                videoDuration = mVideoView.getDuration();
                tvCurrent.setText(KHBUtils.stringForTime(0));
                tvTotal.setText(
                        KHBUtils.stringForTime(mVideoView.getDuration()));
                preparStatus = VIDEO_PREPARED;
                showGetSDcardPermissDialog(0);
                // 设置 MediaPlayer 的 OnSeekComplete 监听
                mediaPlayer.setOnSeekCompleteListener(
                        new MediaPlayer.OnSeekCompleteListener() {
                            @Override
                            public void onSeekComplete(MediaPlayer mp) {
                                // seekTo 方法完成时的回调
                                if (playStatus == PLAY_PAUSE) {
                                    mVideoView.resume();
                                } else {
                                    mVideoView.start();
                                }
                                isPlayVideo = true;
                                if (!isVolumeVideo) {
                                    startPlayAnimation();
                                }
                                // 开始线程，更新进度条的刻度
                                handler.postDelayed(startRunnable, 500);
                                // 开始线程，停止播放
                                handler.postDelayed(stopRunnable,
                                        currEndTime + 300);
                            }
                        });
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                // 发生错误重新播放
                ZToast.makeText(DubVideoRecordingActivity.this, "播放出错",
                        ZToast.LENGTH_SHORT).show();
                isPlayVideo = false;
                return false;
            }
        });
        mVideoView
                .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // 在播放完毕被回调
                        isPlayVideo = false;
                    }
                });
        // IVUtils.setImageWidth200(mVideoView.thumbImageView,
        // mWorkContent.getCover());
    }

    private void initView() {
        title = "配音";
        setTitleText(title);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                if (dubViewStatus == 3) {
                    finish();
                } else {
                    showDialog();
                }
            }
        });
        showDubingView();
    }

    @Override
    protected void loadData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mVideoView != null) {
            if (isPlayVideo) {
                stopPlayAnimation();
            }
            mVideoView.pause();
            isPlayVideo = false;
        }
        AudioPlayer.getInstance().stop();
        KHBVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(startRunnable);
        handler.removeCallbacks(stopRunnable);
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mRecorderHandler != null) {
            mRecorderHandler.removeCallbacksAndMessages(null);
        }
        AudioPlayer.getInstance().stop();
        KHBVideoPlayer.releaseAllVideos();
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY:
                    break;
            }
        } else {
            if (requestCode == RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY) {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.play_mode_mute_bt) {
            // 播放
            mVideoView.start();
        } else if (i == R.id.rl_dub_video_concat) {
            mixVideotime = 0;
            //合成配音
            if (getUnRecordPostion() == -1) {
                composeAllAudio();
            } else {
                ZToast.makeText(DubVideoRecordingActivity.this, "还有暂未完成的配音",
                        ZToast.LENGTH_SHORT).show();
            }
        } else if (i == R.id.rl_dub_result_submit) {

            if (txDubResultSubmit.getText().equals("上传配音")) {
                // 上传配音
                submitVideo();
            } else {
                finish();
            }
        }
    }

    /**
     * 所有的配音合成
     */
    private void composeAllAudio() {
        List<String[]> commandList = new ArrayList<>();
        String[] common = getmixAudioToVideo(sentences, localMuxAudioPath,
                localDubAudioPath);
        commandList.add(common);
        String[] extractAudioAndVideo = FFmpegUtil.mediaMux(localOnlyVideoPath,
                localDubAudioPath, localMixDubVideoPath);
        commandList.add(extractAudioAndVideo);
        if (ffmpegHandler != null) {
            int_ffmpeg = 2;
            downloadMsg = "合成中, 请稍等...";
            ffmpegHandler.executeFFmpegCmds(commandList);
        }
    }

    /**
     * 视频和背景音乐合成
     */
    private void composeMusicAndAudio() {
        File localDubAudioFile = new File(localDubAudioPath);
        if (localDubAudioFile.exists()) {
            String[] extractAudioAndVideo = FFmpegUtil.mediaMux(
                    localOnlyVideoPath, localDubAudioPath,
                    localMixDubVideoPath);
            if (ffmpegHandler != null) {
                int_ffmpeg = 3;
                downloadMsg = "视频和背景音乐合成";
                ffmpegHandler.executeFFmpegCmd(extractAudioAndVideo);
            }
        } else {
            ZToast.makeText(DubVideoRecordingActivity.this, "视频配音开始合成失败",
                    ZToast.LENGTH_SHORT).show();
        }
    }

    /**
     * 视频和背景音乐合成
     *
     * @param sentence
     */
    private void composeVideo(Sentence sentence) {
        localDubAudioPath = ESystem.getDubingVideoPath() + File.separator
                + StringUtils.md5(mWorkContent.getVideoUrl()) + "_dubing.mp4";
        String startTime = KHBUtils.stringForTimeTread(sentence.getStart());
        String endTime = KHBUtils.stringForTimeTread(videoDuration);
        String[] common = FFmpegUtil.mixAudioAndVideo(localVideoPath,
                sentence.getSoundUrl(), localDubAudioPath);
        if (ffmpegHandler != null) {
            downloadMsg = "视频开始合成";
            ffmpegHandler.executeFFmpegCmd(common);
        }
    }

    private void showProgressLoading() {
        showMiddleProgressBar(title);
        // showCricleProgress(title);
    }

    private void dismissProgress() {
        hideMiddleProgressBar();
        // hideCricleProgress();
    }

    /**
     * 设置句子列表
     *
     * @param sentencesDetails
     * @return
     */
    public void setParagraphText(List<SentencesDetail> sentencesDetails) {
        if (sentences == null) {
            sentences = new ArrayList<Sentence>();
        }
        for (SentencesDetail sentencesDetail : sentencesDetails) {
            Sentence sentence = new Sentence();
            sentence.setTextId(sentencesDetail.getVersionId());
            String name = sentencesDetail.getName().trim();
            sentence.setSentenceMp3(sentencesDetail.getAudioUrl());
            sentence.setImgUrl(sentencesDetail.getImgUrl());
            String replaceEvaluateText = SpeechUtils.replaceEvaluateText(name);
            String replaceAsSpace_str = SpeechUtils
                    .replaceAsSpace(replaceEvaluateText);
            String[] words = replaceAsSpace_str.split(" |…");
            sentence.setText(name);
            List<WordDetail> wordDetails = new ArrayList<WordDetail>();
            int wordsLength = words.length;
            for (int z = 0; z < wordsLength; z++) {
                WordDetail wordDetail = new WordDetail();
                String text = words[z];
                wordDetail.setText(text);
                wordDetail.setColor(
                        getResources().getColor(R.color.default_text_color));
                wordDetails.add(wordDetail);
            }
            sentence.setWordDetails(wordDetails);
            if (!TextUtils.isEmpty(sentencesDetail.getTranslate())) {
                sentence.setTranslate(sentencesDetail.getTranslate());
            }
            if (sentencesDetail.getStart() != null
                    && sentencesDetail.getStart().trim() != "") {
                try {
                    sentence.setStart(Integer
                            .parseInt(sentencesDetail.getStart().trim()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (sentencesDetail.getDuration() != null
                    && sentencesDetail.getDuration().trim() != "") {
                try {
                    sentence.setDuration(Integer
                            .parseInt(sentencesDetail.getDuration().trim()));
                } catch (Exception e) {
                    CWLog.e("byou", "sentencesDetail.getDuration()转换出错。。。");
                    e.printStackTrace();
                }
            }
            sentences.add(sentence);
            SentenceAnswerBean curSentenceAnswerBean = new SentenceAnswerBean(
                    sentence,
                    getSoundPath(sentence, currPosition).getAbsolutePath(),
                    sentence.getDuration() + 400, "", "", "", 0, 0, 0);
            sentenceAnswers.add(curSentenceAnswerBean);
        }
    }

    /**
     * 点击单个事件
     *
     * @param position
     */
    protected void playPositionVideo(int position) {
        try {
            if (isRecord) {
                return;
            }
            if (currPosition == position && !isVolumeVideo) {
                if (isPlayVideo) {
                    return;
                }
            }
            if (mMediaPlayer != null) {
                mMediaPlayer.setVolume(1f, 1f);
            }
            stopPreviousVideo(false);
            AudioPlayer.getInstance().stop();
            Sentence sentence = sentences.get(position);
            if (null != sentence) {
                // 点击开始播放
                sentence.setSelect(true);
                currViewHolde = (DubVideoRecordingAdapter.BookDeskViewHolder) mRvBookDesk
                        .findViewHolderForLayoutPosition(position);
                currViewHolde.item_speech_tv
                        .setTextColor(getResources().getColor(R.color.black));
                currViewHolde.rel_play_recored_dubing
                        .setVisibility(View.VISIBLE);
                currViewHolde.play_record_iocn.setTimeAndPlayBtnState(
                        (long) sentence.getDuration() + 500,
                        PlayStateView.RECORD_STATUE);
                currViewHolde.play_dubing_iocn.setTimeAndPlayBtnState(
                        (long) sentence.getDuration() + 400,
                        PlayStateView.PLAY_STATUE);
                currPosition = position;
                isVolumeVideo = false;
                playVideo(sentence.getStart(), sentence.getDuration());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 静音播放
     *
     * @param sentence
     */
    protected void playVolumeVideo(Sentence sentence) {
        try {
            if (mMediaPlayer != null) {
                mMediaPlayer.setVolume(0f, 0f);
            }
            if (null != sentence) {
                isVolumeVideo = true;
                playVideo(sentence.getStart(), sentence.getDuration());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopPreviousVideo(boolean isRecord) {
        if (currPosition >= 0) {
            Sentence currSentence = sentences.get(currPosition);
            if (currSentence != null) {
                currSentence.setSelect(false);
            }
        }
        if (currViewHolde != null) {
            if (!isRecord) {
                currViewHolde.item_speech_tv.setTextColor(getResources()
                        .getColor(R.color.default_dub_text_color));
                currViewHolde.rel_play_recored_dubing.setVisibility(View.GONE);
            }
            stopPlayAnimation();
        }
    }

    /**
     * 开始播放动画
     */
    private void startPlayAnimation() {
        currViewHolde.play_iocn
                .setImageResource(R.drawable.reread_bg_annimation);
        final AnimationDrawable animationDrawable = (AnimationDrawable) currViewHolde.play_iocn
                .getDrawable();
        animationDrawable.start();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * 停止播放动画
     */
    private void stopPlayAnimation() {
        if (isPlayVideo) {
            Drawable drawable = currViewHolde.play_iocn.getDrawable();
            if (drawable != null && drawable instanceof AnimationDrawable) {
                ((AnimationDrawable) drawable).stop();
            }
        }
        currViewHolde.play_iocn.setImageResource(R.mipmap.new_icon_sound_1);

    }

    protected void playVideo(int msec, int endTime) {
        if (preparStatus == VIDEO_PREPARED) {
            handler.removeCallbacks(stopRunnable);
            CWLog.d("byou", "开始播放位置：" + msec);
            CWLog.d("byou", "播放时间：" + endTime);
            mSeekBar.setProgress(msec);
            mVideoView.seekTo(msec);
            tvCurrent.setText(KHBUtils.stringForTime(msec));
            currEndTime = endTime;
        } else {
            ZToast.makeText(DubVideoRecordingActivity.this, "视频暂未加载完成",
                    ZToast.LENGTH_SHORT).show();
        }

    }

    protected void stopVideo() {
        if (mVideoView.isPlaying()) {
            mVideoView.stopPlayback();
        }
    }

    public String mUuid = UUID.randomUUID().toString();


    /**
     * 获取录音的地址
     *
     * @param sentence
     * @return
     */
    private File getSoundPath(Sentence sentence, int index) {
        return new File(
                ESystem.getDubingAnswersUserAudioPath(
                        mWorkContent.getVersionId(), mUuid),
                mUuid + StringUtils.md5(sentence.getText() + index)
                        + EConstants.AUDIO_DEFAULT_SUFFIX);
    }

    /**
     * 获取录音合成的地址
     *
     * @return
     */
    private File getDubingPath() {
        return new File(
                ESystem.getDubingAnswersUserAudioPath(
                        mWorkContent.getVersionId(), mUuid),
                StringUtils.md5(mWorkContent.getVersionId() + mUuid)
                        + "_dubing.aac");
    }

    /**
     * 获取录音合成的地址
     *
     * @return
     */
    private File getMixDubingPath() {
        return new File(
                ESystem.getDubingAnswersUserAudioPath(
                        mWorkContent.getVersionId(), mUuid),
                StringUtils.md5(mWorkContent.getVersionId() + mUuid)
                        + "_mix_dubing.mp4");
    }

    /**
     * 录音
     */
    protected void record() {
        if (isRecord) {
            return;
        }
        if (isPlayVideo) {
            stopPreviousVideo(true);
            if (mVideoView != null) {
                mVideoView.pause();
                isPlayVideo = false;
            }
        }
        if (isPlayDubVideo) {
            mLastPlayIcon.stopOnlyPlay();
            AudioPlayer.getInstance().stop();
            isPlayDubVideo = false;
        }
        currViewHolde.play_record_iocn.startRecordHandler();
        try {
            //获取评分文本
            Sentence sentence = sentences.get(currPosition);
            playVolumeVideo(sentence);
            String sentenceText = sentence.getText();
            String processText = SpeechUtils.replaceEvaluateText(sentenceText);
            processText = SpeechUtils.replaceAsSpace(processText);
            startRecorder(sentence);
        } catch (OutOfMemoryError error) {
            isRecord = false;
            error.getStackTrace();
        }
    }

    /**
     * 开始录制
     */
    private void startRecorder(Sentence sentence) {
        //音频保存地址
        String mRecorderPath = getSoundPath(sentence, currPosition).getAbsolutePath();
        CWLog.d(TAG, "开始录音");
        mp3Recorder = new Mp3Recorder(mRecorderPath, BaseConstants.SAMPLERATE, mRecorderHandler);
        mp3Recorder.setOnRecorderListener(new OnRecorderListener() {
            @Override
            public void onRecorderListener(int msgType) {
                CWLog.d(TAG, "######onRecorderListener msgType#########" + msgType);
            }
        });
        mp3Recorder.start();
    }

    /**
     * 录音回调
     */
    Handler mRecorderHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            try {
                if (isFinishing()) {
                    return true;
                }
                CWLog.d(TAG, "########录音msg.what#########" + msg.what);
                switch (msg.what) {//mp3Record  start 后，由jar 包里发出Mp3Recorder.MSG_REC_STARTED 消息
                    case Mp3Recorder.MSG_REC_STARTED:// 录音开始
                        CWLog.d(TAG, "########录音倒计时#########");
                        // 开始录音
                        isRecord = true;
                        try {
                            Sentence sentence = sentences.get(currPosition);
                            // 开始线程，录音倒计时，停止录音
                            handler.postDelayed(stopRecordRunnable,
                                    sentence.getDuration() + 500);
                        } catch (Exception e) {
                        }
                        mRecordSoundDb = 0;
                        break;
                    case Mp3Recorder.MSG_DB:// 录音分贝
                        Bundle b = msg.getData();
                        if (b != null) {
                            double db = b.getDouble("db");
                            //CWLog.d(TAG, "########录音音量#########"+db);
                            if (!Double.isNaN(db)) {
                                int soundDb = Double.valueOf(db).intValue();
                                if (soundDb > mRecordSoundDb) {
                                    mRecordSoundDb = soundDb;
                                }
                            } else {
                                CWLog.d(TAG, "########Double.isNaN(db)#########" + db);
                            }
                        }
                        break;
                    case Mp3Recorder.MSG_ERROR_AUDIO_RECORD:// 录音失败
                        CWLog.d(TAG, "########     Mp3Recorder.MSG_ERROR_AUDIO_RECORD    录音失败#########");
                        //出现录音失败就不应该继续做题
                        isRecordFail = true;
                        DialogUtil.showSettingPermissions(DubVideoRecordingActivity.this);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_AUDIO_RECORD", "录音失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_REC_START:
                        CWLog.d(TAG, "########     Mp3Recorder.MSG_ERROR_AUDIO_RECORD    录音失败#########");
                        //出现录音失败就不应该继续做题
                        isRecordFail = true;
                        DialogUtil.showSettingPermissions(DubVideoRecordingActivity.this);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_REC_START", "录音失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_AUDIO_ENCODE:
                        ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, "录音处理编码失败，请重新作答！", R.mipmap.ic_increase_volume);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_AUDIO_ENCODE", "录音处理编码失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_WRITE_FILE:
                        ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, "录音读取文件失败，请重新作答！", R.mipmap.ic_increase_volume);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_WRITE_FILE", "录音读取文件失败回调");
                        break;
                    case Mp3Recorder.MSG_ERROR_CLOSE_FILE:
                        ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, "录音关闭读取失败，请重新作答！", R.mipmap.ic_increase_volume);
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_ERROR_CLOSE_FILE", "录音关闭读取失败回调");
                        break;
                    case Mp3Recorder.MSG_REC_STOPPED:// 录音结束
                        CWLog.d(TAG, "########录音结束#########");
                        readCount++;
                        try {
                            if (isRecordFail) {
                                isRecord = false;
                                ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, "录音结束失败，请重新录音！", R.mipmap.ic_increase_volume);
                                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音失败回调：Mp3Recorder.MSG_REC_STOPPED", "录音结束失败回调isRecordFail：" + isRecordFail);
                                break;
                            }
                            if (mRecordSoundDb < 55) {
                                ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, R.string.read_sound_too_low_tips, R.mipmap.ic_increase_volume);
                            } else {
                                isSoundToLow = false;
                            }
                            //音频上传
                            onUploadStateDeal(getCurrentLswAnswer());
                        } catch (Exception e) {
                            isRecord = false;
                            ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, "录音结束失败Exception，请重新录音！", R.mipmap.ic_increase_volume);
                            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_MP3RECORDER, "录音回调：Mp3Recorder.MSG_REC_STOPPED：" + e.getMessage(), "录音结束失败Exception");
                            e.getStackTrace();
                        }
                        break;
                    default:
                        isRecord = false;
                        ToastUtil.INSTANCE.toastCenter(DubVideoRecordingActivity.this, "录音失败,未知问题，请重新作答！", R.mipmap.ic_increase_volume);
                        break;
                }

            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            return true;
        }
    });

    /**
     * /** 停止录音
     */
    public void stopRecord() {
        handler.removeCallbacks(stopRecordRunnable);
        if (mp3Recorder != null) {
            mp3Recorder.stop();
        }
        stopRecordView();
    }

    /**
     * 组装提交作业json
     *
     * @param dubbingVideoUrl
     * @return
     */
    private String toJson(String dubbingVideoUrl) {
        sumScore = 0;// 总分数
        totalTime = (int) (System.currentTimeMillis() - startDate) / 1000;
        if (totalTime < 0) {
            totalTime = 0;
        }
        ArrayList<SentenceAnswer.WorkAnswers> workList = new ArrayList<>();
        for (int i = 0; i < sentenceAnswers.size(); i++) {
            SentenceAnswerBean sentenceAnswerBean = sentenceAnswers.get(i);
            sumScore = sentenceAnswerBean.getSentence().getScore() + sumScore;
            SentenceAnswer.Answers answers = new SentenceAnswer.Answers(
                    sentenceAnswerBean.getSentence().getText(),
                    sentenceAnswerBean.getUrlLiYun(),
                    sentenceAnswerBean.getReadTimes(),
                    sentenceAnswerBean.getAudioDuration(),
                    sentenceAnswerBean.getLines(), sentenceAnswerBean.getYzsAudioUrl(), sentenceAnswerBean.getFluency(), sentenceAnswerBean.getIntegrity(), sentenceAnswerBean.getPronunciation());
            ArrayList<SentenceAnswer.Answers> anList = new ArrayList<>();
            anList.add(answers);
            SentenceAnswer.WorkAnswers workAnswers = new SentenceAnswer.WorkAnswers(
                    sentenceAnswerBean.getSentence().getTextId(),
                    sentenceAnswerBean.getSentence().getScore(), 4, anList);
            workList.add(workAnswers);
        }
        sumScore = sumScore / sentenceAnswers.size();
        sentenceAnswerModle = new SentenceAnswer();
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        if (userInfo != null) {
            sentenceAnswerModle.setUserName(userInfo.getRealName());
        }
        sentenceAnswerModle.setWorkId(workId);
        sentenceAnswerModle.setStartTime(workStartTime);
        sentenceAnswerModle.setSessionId(mUuid);
        sentenceAnswerModle.setPackageId(mWorkContent.getPackageId());
        sentenceAnswerModle.setcId(mWorkContent.getcId());
        sentenceAnswerModle.setClassId(classId);
        sentenceAnswerModle.setModuleId(mWorkContent.getModuleId());
        sentenceAnswerModle.setResourceName(mWorkContent.getResourceName());
        sentenceAnswerModle
                .setParentVersionId(mWorkContent.getParentVersionId());
        sentenceAnswerModle.setVersionId(mWorkContent.getVersionId());
        sentenceAnswerModle.setResourceType(mWorkContent.getResourceType());
        sentenceAnswerModle.setWorkLong(totalTime);
        sentenceAnswerModle.setDoWorkPackageUrl("");
        sentenceAnswerModle.setActualScore(Math.round(sumScore));
        sentenceAnswerModle.setBrandId(EApplication.BRAND_ID);
        sentenceAnswerModle.setWorkType(mWorkContent.getWorkType());
        sentenceAnswerModle.setContentId(contentId);
        sentenceAnswerModle.setWorkScore(100);
        sentenceAnswerModle.setWorkAnswers(workList);
        sentenceAnswerModle
                .setAvatorUrl(getUserInfoBase().getAvatar() == null ? ""
                        : getUserInfoBase().getAvatar());
        sentenceAnswerModle.setCover(mWorkContent.getCover());
        sentenceAnswerModle.setVideoUrl(mWorkContent.getVideoUrl());
        sentenceAnswerModle.setDubbingVideoUrl(dubbingVideoUrl);
        return sentenceAnswerModle.toString();
    }

    /**
     * 开始上传视频配音
     */
    private void submitVideo() {
        File localMixDubVideoFile = new File(localMixDubVideoPath);
        if (localMixDubVideoFile.exists()) {
            downloadMsg = "上传中，请稍等...";
            showDownloadProgress(downloadMsg);
            String photoUrlKey = ALiYunManager.getInstance()
                    .getDubKey(localMixDubVideoPath);
            ALiYunManager.getInstance().addFile(localMixDubVideoPath,
                    photoUrlKey, localMixDubVideoPath);
        } else {
            ZToast.makeText(DubVideoRecordingActivity.this, "视频配音不存在，请重新配音.",
                    ZToast.LENGTH_SHORT).show();
        }

    }

    private SentenceAnswerBean itme = new SentenceAnswerBean();

    /**
     * 监听上传
     */
    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {
            if (tag != null) {
                try {
                    String photoPath = tag.toString();
                    if (localMixDubVideoPath.equals(photoPath)) {
                        if (currentSize > 0 && totalSize > 0) {
                            long progress = currentSize * 100 / totalSize;
                            if (progress < 100) {
                                updateDownloadProgress((int) progress);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onSuccess(Object tag, String url) {
            try {
                String photoPath = tag.toString();
                if (localMixDubVideoPath.equals(photoPath)) {
                    // 上传成功
                    isCheckSubmit = true;
                } else {
                    itme.setSoundUrl(photoPath);
                    if (sentenceAnswers.indexOf(itme) != -1) {
                        sentenceAnswers.get(sentenceAnswers.indexOf(itme))
                                .setUrlLiYun(url);
                    }
                }
                checkSubmit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
                try {
                    String photoPath = String.valueOf(tag);
                    if (localDubAudioPath.equals(photoPath)) {
                        hideDownloadProgress();
                        ZToast.makeText(DubVideoRecordingActivity.this,
                                "上传失败，请稍后重试！", ZToast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private void checkSubmit() {
        if (!isCheckSubmit) {
            return;
        }
        int isAll = 0;
        for (int i = 0; i < sentenceAnswers.size(); i++) {
            if (sentenceAnswers.get(i).getUrlLiYun().equals("")) {
                isAll = -1;
                break;
            }
        }
        if (isAll == 0) {
            String url = ALiYunManager.ACCESS_URL + ALiYunManager.getInstance()
                    .getDubKey(localMixDubVideoPath);
            submit(url);
        }
    }

    /**
     * 提交Json
     */
    private void submit(String dubbingVideoUrl) {
        final String dataJson = toJson(dubbingVideoUrl);
        CWLog.d(TAG,
                "提交配音" + System.currentTimeMillis() + "tag===json=" + dataJson);
        EpaperDao.getInstance().submitDubingVideo(dataJson,
                ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT,
                sentenceAnswerModle.getWorkId(),
                sentenceAnswerModle.getContentId(),
                new BaseExtCallBack(DubVideoRecordingActivity.this,
                        EApplication.getInstance().getUserInfoBase().getUserId()
                                + "") {

                    @Override
                    public void success(Object data) {
                        hideDownloadProgress();
                        CWLog.d(TAG, "提交配音json成功" + System.currentTimeMillis()
                                + "tag===json");
                        submitResult = (SubmitResult) data;
                        doWorkId = submitResult.getDoWorkId();
                        if (null != submitResult) {
                            showDubingSubmitFinishView();
                        }
                        clearRecord();
                        Intent intent = new Intent(
                                EpaperConstant.INTENT_BOACK_REF_WORK);
                        intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE,
                                sumScore);
                        intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, 1);
                        sendBroadcast(intent);
                    }

                    @Override
                    public void failed(Object data) {
                        hideDownloadProgress();
                        CWLog.d(TAG, "提交配音json失败" + System.currentTimeMillis()
                                + "tag===json");
                        ZToast.makeText(DubVideoRecordingActivity.this,
                                "上传配音失败,请稍后重试！", ZToast.LENGTH_SHORT).show();
                        if (null != data) {
                            FeedbackUtil.getInstance().addFeedbackLogWithJson(
                                    FeedbackUtil.FEEDBACK_TYPE_SENTENCE_SPEECH,
                                    data.toString(), dataJson,
                                    "句子提交配音作业失败：" + getUrl());
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        hideDownloadProgress();
                        CWLog.d(TAG, "提交配音json失败" + System.currentTimeMillis()
                                + "tag===json");
                        ZToast.makeText(DubVideoRecordingActivity.this,
                                "上传配音失败,请稍后重试！", ZToast.LENGTH_SHORT).show();
                        if (null != data) {
                            FeedbackUtil.getInstance().addFeedbackLogWithJson(
                                    FeedbackUtil.FEEDBACK_TYPE_SENTENCE_SPEECH,
                                    data.toString(), dataJson,
                                    "句子提交配音作业失败：" + getUrl());
                        }
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 返回键监听
            if (dubViewStatus == 3) {
                finish();
            } else {
                showDialog();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 提示退出框
     */
    protected void showDialog() {
        if (mDialog == null) {
            mDialog = new CWDialog(this);
            mDialog.setMessage(R.string.confirm_dubing_work);
            mDialog.setPositiveButton(android.R.string.cancel, null);
            mDialog.setNegativeButton(R.string.sure,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (dubViewStatus == 2) {
                                showDubingView();
                            } else {
                                finish();
                            }
                        }
                    });
        }
        mDialog.setMessage(dub_status == 1 ? R.string.confirm_dubing_submit
                : R.string.confirm_dubing_work);
        mDialog.show();
    }

    /**
     * ArrayList<String>转String[]
     *
     * @param commList
     * @return
     */
    private String[] commListToArr(ArrayList<String> commList) {
        String[] commands = new String[commList.size()];
        for (int i = 0; i < commList.size(); i++) {
            commands[i] = commList.get(i);
        }
        return commands;
    }

    /**
     * @param sentences  key 对应某段配音 的本地地址 value 配音对应在原视频的 截止时间
     * @param inputPath  视频地址
     * @param outputPath 输出地址
     * @return
     */
    private String[] getmixAudioToVideo(List<Sentence> sentences,
                                        String inputPath, String outputPath) {
        ArrayList<String> commList = new ArrayList<>();
        commList.add("ffmpeg");
        commList.add("-y");
        commList.add("-i");
        commList.add(inputPath);
        String lastCommand = "";
        int index = 0;
        String tip = "_";
        for (int i = 0; i < sentences.size(); i++) {
            Sentence item = sentences.get(i);
            commList.add("-i");
            commList.add(item.getSoundUrl());
            lastCommand += "[" + (i + 1) + "]adelay=" + item.getStart() + "|"
                    + item.getDuration() + "[" + (i + 1) + tip + "];  ";
            if (i == sentences.size() - 1) {
                for (int j = 0; j <= sentences.size(); j++) {
                    if (j == 0) {
                        lastCommand += "[0]";
                    } else if (j == sentences.size()) {
                        lastCommand += "[" + j + tip + "]" + "amix="
                                + (sentences.size() + 1) + "";
                    } else {
                        lastCommand += "[" + j + tip + "]";
                    }
                }

            }
        }
        commList.add("-filter_complex");
        commList.add(lastCommand);
        commList.add(outputPath);
        CWLog.w(TAG, "getmixAudio:" + commList.toString());
        return commListToArr(commList);
    }

    /**
     * 显示配音中界面
     */
    private void showDubingView() {
        dubViewStatus = 1;
        llDubingDoing.setVisibility(View.VISIBLE);
        llDubingResult.setVisibility(View.GONE);
        KHBVideoPlayer.releaseAllVideos();
    }

    /**
     * 显示配音合成完成
     */
    private void showDubingFinishView() {
        dubViewStatus = 2;
        llDubingDoing.setVisibility(View.GONE);
        llDubingResult.setVisibility(View.VISIBLE);
        rlDubResultSubmit.setVisibility(View.VISIBLE);
        ivDubResultFinishTag.setVisibility(View.VISIBLE);
        ivDubResultScoreTag.setVisibility(View.GONE);
        rlDubResultScore.setVisibility(View.GONE);
        txDubResultTip.setText("合成配音成功！");
        txDubResultSentencesNum.setText("完成配音" + sentences.size() + "个句子");
        txDubResultTag.setText("点击上传配音可以在学习记录中随时查看");
        txDubResultSubmit.setText("上传配音");
        mKHBVideoPlayerStandard.setplsyModeUrlUp(localMixDubVideoPath,
                KHBVideoPlayer.SCREEN_LAYOUT_LIST,
                KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
    }

    /**
     * 显示配音提交完成
     */
    private void showDubingSubmitFinishView() {
        txDubResultRelatWX.setVisibility(View.VISIBLE);
        dubViewStatus = 3;
        llDubingDoing.setVisibility(View.GONE);
        llDubingResult.setVisibility(View.VISIBLE);
        rlDubResultSubmit.setVisibility(View.VISIBLE);
        ivDubResultFinishTag.setVisibility(View.GONE);
        ivDubResultScoreTag.setVisibility(View.VISIBLE);
        rlDubResultScore.setVisibility(View.VISIBLE);
        if (serviceExpired) {
            txDubResultScore.setText(sentenceAnswerModle.getActualScore() + "");
            txDubResultScoreTag.setVisibility(View.VISIBLE);
        } else {
            txDubResultScore.setText("已完成");
            txDubResultScoreTag.setVisibility(View.GONE);
        }

        txDubResultTip.setText("上传配音成功！");
        txDubResultSentencesNum.setText("完成配音" + sentences.size() + "个句子");
        txDubResultTag.setText("上传时间："
                + DateUtils.Date2String(new Date(), DateUtils.DATE_LONG));
        txDubResultSubmit.setText("完成");
        mKHBVideoPlayerStandard.setplsyModeUrlUp(localMixDubVideoPath,
                KHBVideoPlayer.SCREEN_LAYOUT_LIST,
                KHBVideoPlayer.PLAY_MODE_UNMUTE, "");
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;
    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetSDcardPermissDialog(final int position) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss(position);
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss(position);
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss(final int position) {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                playPositionVideo(position);
                            } else {
                                // showConfirmCommitDialog(getActivity(),
                                // "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            playPositionVideo(position);
        }
        return true;
    }

    private CWDialog getRecordPermissDialog;

    /**
     * 获取Record权限提示框
     */
    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(this);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用录音，判断权限
     */
    private boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                record();
                            } else {
                                // showConfirmCommitDialog(getActivity(),
                                // "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            record();
        }
        return true;
    }

    /**
     * 上传音频
     *
     * @param lswAnswer
     */
    private void onUploadStateDeal(final LswAnswer lswAnswer) {
        showCricleProgress("评分中...");
        LswRequest.submitAsyncMakeScore(lswAnswer, new BaseCallBack() {
            @Override
            public void success(Object data) {
                CWLog.d(TAG, "###########上传音频成功############" + lswAnswer.getVersionId());
                final RecordSubmitAsyncPart mReult = (RecordSubmitAsyncPart) data;
                final int score = (int) Math.floor(SpeechUtils.scoreOptimize(mReult.getCorrectScore()));
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        hideCricleProgress();
                        try {
                            mDubVideoRecordingAdapter.setScoreResult(
                                    DubVideoRecordingActivity.this, score,
                                    currViewHolde.score_rel,
                                    currViewHolde.score_text, currViewHolde.see_score_text,
                                    currViewHolde.score_fuhao, serviceExpired);
                            Sentence curSentence = sentences.get(currPosition);
                            // 是否已经评分
                            oldHasGrade = curSentence.hasGrade();
                            CorrectLinesRelut mCorrectLinesRelut = mReult.getCorrectBody().getLines().get(0);
                            String lines = JsonParserUtil.toJson(mCorrectLinesRelut);
                            // 如果是最后一个或者是重读都要延迟2秒 用来显示分数用
                            // 音频文件地址
                            curSentence.setLines(lines);
                            curSentence.setUrlLiYun(mReult.getAnswerContent());
                            curSentence.setSoundUrl(
                                    getSoundPath(curSentence, currPosition)
                                            .getAbsolutePath());
                            mDubVideoRecordingAdapter.showSentenceResult(
                                    DubVideoRecordingActivity.this,
                                    currViewHolde.item_speech_tv, mCorrectLinesRelut,
                                    curSentence, false, serviceExpired);
                            SentenceAnswerBean curSentenceAnswerBean = new SentenceAnswerBean(
                                    curSentence,
                                    getSoundPath(curSentence, currPosition)
                                            .getAbsolutePath(),
                                    curSentence.getDuration() + 400, lines, mReult.getAnswerContent(), mReult.getAnswerContent(), mCorrectLinesRelut.getFluency(), mCorrectLinesRelut.getIntegrity(), mCorrectLinesRelut.getPronunciation());
                            sentenceAnswers.set(currPosition,
                                    curSentenceAnswerBean);
                            // 声音过低且分数低于80时给予提示
                            if ((readCount <= 3 && score < 80 && isSoundToLow)) {
                                ToastUtil.INSTANCE.toastCenter(
                                        DubVideoRecordingActivity.this,
                                        R.string.read_sound_too_low_tips,
                                        R.mipmap.ic_increase_volume);
                            }
                            CWLog.e(TAG, "score retryscore2: " + currPosition);
                            isSoundToLow = true;

                            if (currPosition == (sentences.size() - 1)) {
                                // 最后一个录音
                                if (getUnRecordPostion() == -1) {
                                    rlDubVideoConcat.setBackgroundColor(
                                            getResources().getColor(R.color.green));
                                }
                            }
                            isRecord = false;
                            playRecordView();
                        } catch (Exception e) {
                            isRecord = false;
                            e.getStackTrace();
                        }
                    }
                });
                isRecord = false;
            }

            @Override
            public void failed(int errorCode, Object data) {
                failed(data);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "###########上传音频失败############" + lswAnswer.getVersionId());
                if (data != null) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "听说模考上传语音评分失败：" + lswAnswer.getVersionId() + getUrl());
                }
                ToastUtil.INSTANCE.toastCenterError(
                        "评分过程遇到错误，错误信息,请重试。");
                isRecord = false;
            }
        });
    }

    //获取用户当前答案和题目
    private LswAnswer getCurrentLswAnswer() {
        LswAnswer lswAnswer = new LswAnswer();
        try {
            //当前要评测的小题
            Sentence sentence = sentences.get(currPosition);
            String sentenceText = sentence.getText();
            String processText = SpeechUtils.replaceEvaluateText(sentenceText);
            processText = SpeechUtils.replaceAsSpace(processText);
            lswAnswer.setRefScore(100);
            lswAnswer.setQtype(6);
            lswAnswer.setIs_objective(1);
            lswAnswer.setWorkSaveUUid(mUuid);
            lswAnswer.setVersionId(sentence.getTextId());
            lswAnswer.setUploadState(LswAnswer.FAIL);
            lswAnswer.setAnswerType(Questions.AnswerType.QUESTION_TYPE_VOICE);

            List<AnswerContent> answerContents = new ArrayList<AnswerContent>();
            AnswerContent answerContent = new AnswerContent();
            CWLog.d(TAG, "#######评测文本 processText#########" + processText);
            answerContent.setRefAnswer(processText);
            // 音频文件地址
            answerContent.setContent(getSoundPath(sentence, currPosition).getAbsolutePath());
            answerContent.setSid(0);
            answerContents.add(answerContent);
            lswAnswer.setAnswerContents(answerContents);

        } catch (Exception e) {
            e.getStackTrace();
        }
        return lswAnswer;
    }

    /**
     * 清除记录
     */
    private void clearRecord() {
        // 清除本次做作业或自主练习活动key,只有活动key 清
        CWLog.d(TAG, "#######clearRecord #########");
        CWSys.setSharedString(RepeatKeyUtil.getDubbingUuidSaveKey(workId,
                mWorkContent.getVersionId(), mWorkContent.getPackageId(),
                mWorkContent.getcId(), mWorkContent.getModuleId(), contentId),
                null);
        CWSys.setSharedLong(RepeatKeyUtil.getDubbingStartDateSaveKey(workId,
                mWorkContent.getVersionId(), mWorkContent.getPackageId(),
                mWorkContent.getcId(), mWorkContent.getModuleId(), contentId),
                0);
        CWSys.setSharedLong(getStartTimeKey(), 0);
    }
}